package mesweb.mesweb.controller.procedure;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.farvision.common.api.CommonResult;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import mesweb.mesweb.config.ServerConfig;
import mesweb.mesweb.entity.Procedure.MESProcedureSOP;
import mesweb.mesweb.service.procedure.IMESProcedureSOPService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * @Description: 标准指导书
 * @Author: jeecg-boot
 * @Date:   2021-06-17
 * @Version: V1.0
 */

@Api(tags="标准指导书")
@RestController
@RequestMapping("/mes/mESProcedureSOP")
public class MESProcedureSOPController {
	@Autowired
	private IMESProcedureSOPService mESProcedureSOPService;

	@Autowired
	private ServerConfig serverConfig;

	@Value("${file.uploadFolder}")
	private String uploadPath;

    @GetMapping("/GetAll")
    @ApiOperation("获取全部数据列表")
    public CommonResult<?> GetAll(@ApiParam("名称") @RequestParam( value = "name",required = false) String name) {
        List<MESProcedureSOP> data = new ArrayList<>();
        if (StringUtils.isBlank(name) || name.equals("全部")) {
            data = mESProcedureSOPService.list();
        } else {
            QueryWrapper<MESProcedureSOP> queryWrapper = new QueryWrapper<>();
            data = mESProcedureSOPService.list(queryWrapper);
        }
        return CommonResult.success(data);
    }
	/**
	 * 分页列表查询
	 *
	 * @param mESProcedureSOP
	 * @param pageNo
	 * @param pageSize
	 * @param req
	 * @return
	 */
	@ApiOperation(value="标准指导书-分页列表查询", notes="标准指导书-分页列表查询")
	@GetMapping(value = "/list")
	public CommonResult<?> queryPageList(MESProcedureSOP mESProcedureSOP,
								   @RequestParam(name="page", defaultValue="1") Integer page,
								   @RequestParam(name="size", defaultValue="10") Integer size,
								   HttpServletRequest req) {
		QueryWrapper<MESProcedureSOP> queryWrapper = new QueryWrapper<>();
		Page<MESProcedureSOP> pageMESProcedureSOP = new Page<MESProcedureSOP>(page, size);
		IPage<MESProcedureSOP> pageList = mESProcedureSOPService.page(pageMESProcedureSOP, queryWrapper);
		return CommonResult.success(pageList);
	}
	/**
	 * 编辑
	 *
	 * @param mESProcedureSOP
	 * @return
	 */
	@ApiOperation(value="标准指导书-编辑", notes="标准指导书-编辑")
	@PostMapping(value = "/save")
	public CommonResult<?> edit(@RequestBody MESProcedureSOP mESProcedureSOP) {
       boolean result = false;
        if(mESProcedureSOP.getId() == 0L) {
             result = mESProcedureSOPService.save(mESProcedureSOP);
        }
        else
        {
            result = mESProcedureSOPService.updateById(mESProcedureSOP);
        }
        return CommonResult.success(mESProcedureSOP);
	}

	/**
	 * 通过id删除
	 *
	 * @param id
	 * @return
	 */
	@ApiOperation(value="标准指导书-通过id删除", notes="标准指导书-通过id删除")
	@DeleteMapping(value = "/delete")
	public CommonResult<?> delete(@RequestParam(name="id",required=true) String id) {
		mESProcedureSOPService.removeById(id);
		return CommonResult.success("删除成功!");
	}

	/**
	 * 批量删除
	 *
	 * @param ids
	 * @return
	 */
	@ApiOperation(value="标准指导书-批量删除", notes="标准指导书-批量删除")
	@DeleteMapping(value = "/deletePicture")
	public CommonResult<?> deleteBatch(@ApiParam("MESProcedureSOPIDs") @RequestBody List<String> ids) {
		//第一个元素是id，第二个是图片的URL
		if(ids != null && ids.size()>=1)
		{
			MESProcedureSOP mesProcedureSOP =  mESProcedureSOPService.getById(Long.parseLong(ids.get(0)));
			if(mesProcedureSOP != null)
			{
				mesProcedureSOP.setAttachmentFiles(mesProcedureSOP.getAttachmentFiles().replaceFirst(ids.get(1)+";",""));
				mESProcedureSOPService.updateById(mesProcedureSOP);
			}
		}
		return CommonResult.success("批量删除成功！");
	}

	/**
	 * 批量删除
	 *
	 * @param ids
	 * @return
	 */
	@ApiOperation(value="标准指导书-批量删除", notes="标准指导书-批量删除")
	@DeleteMapping(value = "/deleteBatch")
	public CommonResult<?> deletePicture(@ApiParam("MESProcedureSOPIDs") @RequestBody List<String> ids) {
		//第一个元素是id，第二个是图片的URL
		if(ids != null && ids.size()>=1)
		{
		     mESProcedureSOPService.removeByIds(ids);
		}
		return CommonResult.success("批量删除成功！");
	}

	/**
	 * 通过id查询
	 *
	 * @param id
	 * @return
	 */
	@ApiOperation(value="标准指导书-通过id查询", notes="标准指导书-通过id查询")
	@GetMapping(value = "/queryById")
	public CommonResult<?> queryById(@RequestParam(name="procedureId",required=true) Long id) {
		QueryWrapper queryWrapper = new QueryWrapper();
		queryWrapper.eq("procedure_id",id);
	    MESProcedureSOP mESProcedureSOP = mESProcedureSOPService.getOne(queryWrapper);
		return CommonResult.success(mESProcedureSOP);
	}

    @PostMapping("/upload")
    @ResponseBody
    public CommonResult<?> upload(@RequestParam("file") MultipartFile file,@RequestParam("id") Long id) {
        if (file.isEmpty()) {
            return  CommonResult.failed("上传失败，请选择文件");
        }

        String fileName = file.getOriginalFilename();
        //String filePath = "/resources/upload/";
        File dest = new File(uploadPath + fileName);
        try {
            file.transferTo(dest);
			MESProcedureSOP mesProcedureSOP =  mESProcedureSOPService.getById(id);
			if(mesProcedureSOP != null)
			{
				mesProcedureSOP.setAttachmentFiles(mesProcedureSOP.getAttachmentFiles() + serverConfig.getUrl() +  fileName+";");
				mESProcedureSOPService.updateById(mesProcedureSOP);
			}
            return CommonResult.success(serverConfig.getUrl() +  fileName);
        } catch (IOException e) {
           return  CommonResult.failed(e.getMessage());
        }
    }
}
